package com.csoa.community.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;

import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.csoa.community.R;
import com.csoa.community.bean.UserBean;
import com.csoa.community.net.ErrorMsg;
import com.csoa.community.net.WcfAsyncTask;
import com.csoa.community.requests.AbstractRequest;
import com.csoa.community.requests.LoginRequest;
import com.csoa.community.singletons.GlobalVars;
import com.csoa.community.utils.AndroidUtils;
import com.csoa.community.utils.StringUtils;

public class LoginActivity extends BaseActivity {

	private EditText usernameET;
	private EditText passwordET;
	private CheckBox remUsernameCheck;
	private CheckBox remPasswordCheck;
	private LinearLayout remUsernameLayout;
	private LinearLayout remPasswordLayout;
	private Button btnLogin;
	private RadioGroup autoLoginRadioGroup;
	private RadioButton yesAutoLogin;
	private RadioButton noAutoLogin;

	@Override
	public void initUI() {
		setContentView(R.layout.login);
		ErrorMsg.init(this);
		//设置获取列表数据的指定时间
		GlobalVars.DataCount = SettingActivity.getDataTime(this) * 100;
		 
		File file = new File(GlobalVars.getInst().getAttachPath());
		if (!file.exists()) {
			file.mkdir();
		}

		usernameET = (EditText) this.findViewById(R.id.username_et_login);
		passwordET = (EditText) this.findViewById(R.id.password_et_login);

		remUsernameCheck = (CheckBox) this
				.findViewById(R.id.rem_username_check_login);
		remPasswordCheck = (CheckBox) this
				.findViewById(R.id.rem_password_check_login);

		remUsernameLayout = (LinearLayout) this
				.findViewById(R.id.rem_username_layout_login);

		autoLoginRadioGroup = (RadioGroup) this
				.findViewById(R.id.auto_login_RadioGroup_login);
		autoLoginRadioGroup
				.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(RadioGroup group, int checkedId) {
						if (checkedId == R.id.yes_auto_login) {
							remUsernameCheck.setChecked(true);
							remPasswordCheck.setChecked(true);
						}

					}
				});
		yesAutoLogin = (RadioButton) this.findViewById(R.id.yes_auto_login);
		noAutoLogin = (RadioButton) this.findViewById(R.id.no_auto_login);

		// remUsernameCheck.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// changeCheckState(remUsernameCheck);
		//
		// }
		// });
		//
		// remPasswordCheck.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// changeCheckState(remPasswordCheck);
		//
		// }
		// });
		//
		//
		remUsernameLayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				changeCheckState(remUsernameCheck);

			}
		});
		remPasswordLayout = (LinearLayout) this
				.findViewById(R.id.rem_password_layout_login);
		remPasswordLayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				changeCheckState(remPasswordCheck);

			}
		});

		btnLogin = (Button) this.findViewById(R.id.login_btn_login);
		btnLogin.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				String strUsername = usernameET.getEditableText().toString();
				if (StringUtils.isEmpty(strUsername)) {
					LoginActivity.this.showToast("用户名不能为空");
					return;
				}
				String strPassword = passwordET.getEditableText().toString();
				if (StringUtils.isEmpty(strPassword)) {
					LoginActivity.this.showToast("密码不能为空");
					return;
				}

				clearComWordIfSwitchUsername(strUsername);

				// 点击登录按钮出发操作
				buildRequestLogin(strUsername, strPassword);

			}
		});

		initFillView();

	}

	/**
	 * 如果切换账户，删除常用语缓存记录
	 * 
	 * @param strUsername
	 */
	protected void clearComWordIfSwitchUsername(String strUsername) {
		String localUsername = AndroidUtils.getGlobal(GlobalVars.LOGIN,
				GlobalVars.LOGIN_USERNAME, LoginActivity.this);

		if (localUsername == null || !localUsername.equals(strUsername)) {
			AndroidUtils.setGlobal("ComWord", "strComWord", "",
					LoginActivity.this);
			//重置屏幕亮度
			AndroidUtils
			.setGlobal(GlobalVars.LOGIN,
					GlobalVars.LOGIN_CURRENT_SCREEAN_BRIGHT, "",
					LoginActivity.this);
			AndroidUtils.adjustScreenBright(LoginActivity.this,-1);
		}

	}

	protected void buildRequestLogin(String aUsername, String aPassword) {
		showProgress();
		List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("LogName", aUsername));
		params.add(new BasicNameValuePair("Pwd", aPassword));
		netRequestLogin(new LoginRequest(params));
	}

	private void netRequestLogin(AbstractRequest request) {
		new WcfAsyncTask(this, new OnUICallback() {

			@Override
			public void onGetResult(AbstractRequest request) {
				dismisProgress();
				LoginRequest loginRequest = (LoginRequest) request;
				if (loginRequest.user != null
						&& !StringUtils.isEmpty(loginRequest.user.loginName)) {
					if (yesAutoLogin.isChecked()) {
						loginRequest.user.isLogin = true;
					} else {
						loginRequest.user.isLogin = false;
					}
					GlobalVars.currentUser = loginRequest.user;
					saveRemState(GlobalVars.currentUser);
					LoginActivity.this.showToast("登录成功");
					startActivity();
					// LoginActivity.this.setResult(RESULT_OK);
					// finish();
				} else {
					LoginActivity.this.showToast("登录失败,用户名或密码错误");
				}
			}

			@Override
			public void onCancel() {
				dismisProgress();
			}

			@Override
			public void onProgress(int progress, String msg) {
				dismisProgress();
				LoginActivity.this.showToast(msg);
			}
		}).execute(request);
	}

	protected void startActivity() {
		Intent intent = new Intent(this, MainActivity.class);
		startActivity(intent);
		finish();
	}

	private void initFillView() {
		String strRemUsername = AndroidUtils.getGlobal(GlobalVars.LOGIN,
				GlobalVars.LOGIN_IS_REMEMBER_USERNAME, this);
		if (StringUtils.isEmpty(strRemUsername) || strRemUsername.equals("0")) {
			remUsernameCheck.setChecked(false);
		} else {
			remUsernameCheck.setChecked(true);
		}

		String strRemPassword = AndroidUtils.getGlobal(GlobalVars.LOGIN,
				GlobalVars.LOGIN_IS_REMEMBER_PASSWORD, this);
		if (StringUtils.isEmpty(strRemPassword) || strRemPassword.equals("0")) {
			remPasswordCheck.setChecked(false);
		} else {
			remPasswordCheck.setChecked(true);
		}

		String strAutoLogin = AndroidUtils.getGlobal(GlobalVars.LOGIN,
				GlobalVars.LOGIN_IS_AUTO_LOGIN, this);
		if (StringUtils.isEmpty(strAutoLogin) || strAutoLogin.equals("0")) {
			noAutoLogin.setChecked(true);
		} else {
			yesAutoLogin.setChecked(true);
		}

		if (remUsernameCheck.isChecked()) {
			String strUsername = AndroidUtils.getGlobal(GlobalVars.LOGIN,
					GlobalVars.LOGIN_USERNAME, this);
			usernameET.setText(strUsername);
		}

		if (remPasswordCheck.isChecked()) {
			String strPassword = AndroidUtils.getGlobal(GlobalVars.LOGIN,
					GlobalVars.LOGIN_PASSWORD, this);
			passwordET.setText(strPassword);
		}

		// if (StringUtils.isEmpty(usernameET.getText().toString())) {
		// usernameET.setText("administrator");
		// // usernameET.setText("lubin");
		// }
		// //
		// if (StringUtils.isEmpty(passwordET.getText().toString())) {
		// passwordET.setText("cshb");
		// }

	}

	/**
	 * 保存登录状态
	 * 
	 * @param currentUser
	 */
	public void saveRemState(UserBean currentUser) {
		AndroidUtils.setGlobal(GlobalVars.LOGIN, GlobalVars.LOGIN_USERNAME,
				usernameET.getText().toString(), this);

		AndroidUtils.setGlobal(GlobalVars.LOGIN,
				GlobalVars.LOGIN_REALLY_USERNAME, currentUser.userName, this);

		AndroidUtils.setGlobal(GlobalVars.LOGIN, GlobalVars.LOGIN_PASSWORD,
				passwordET.getText().toString(), this);
		AndroidUtils.setGlobal(GlobalVars.LOGIN,
				GlobalVars.LOGIN_IS_REMEMBER_USERNAME,
				remUsernameCheck.isChecked() ? "1" : "0", this);
		AndroidUtils.setGlobal(GlobalVars.LOGIN,
				GlobalVars.LOGIN_IS_REMEMBER_PASSWORD,
				remPasswordCheck.isChecked() ? "1" : "0", this);

		AndroidUtils.setGlobal(GlobalVars.LOGIN,
				GlobalVars.LOGIN_IS_AUTO_LOGIN, yesAutoLogin.isChecked() ? "1"
						: "0", this);
	}

	public void changeCheckState(CheckBox aCheckBox) {
		if (aCheckBox.isChecked()) {
			aCheckBox.setChecked(false);
			if (aCheckBox == remUsernameCheck) {
				remPasswordCheck.setChecked(false);
			}
		} else {
			aCheckBox.setChecked(true);
			if (aCheckBox == remPasswordCheck) {
				remUsernameCheck.setChecked(true);
			}
		}
	}

	@Override
	public void initData() {
		if (GlobalVars.currentUser != null && GlobalVars.currentUser.isLogin) {
			startActivity();
			return;
		}
		String strIsAutoLogin = AndroidUtils.getGlobal(GlobalVars.LOGIN,
				GlobalVars.LOGIN_IS_AUTO_LOGIN, LoginActivity.this);

		String logout = this.getIntent().getStringExtra("logout");
		if (!StringUtils.isEmpty(logout) && logout.equals("logout")) {
			strIsAutoLogin = "0";
			yesAutoLogin.setChecked(false);
			noAutoLogin.setChecked(true);
			AndroidUtils.setGlobal(GlobalVars.LOGIN,
					GlobalVars.LOGIN_IS_AUTO_LOGIN, yesAutoLogin.isChecked() ? "1"
							: "0", this);
		}

		if (strIsAutoLogin != null && "1".equals(strIsAutoLogin)) {
			String username = AndroidUtils.getGlobal(GlobalVars.LOGIN,
					GlobalVars.LOGIN_USERNAME, LoginActivity.this);
			String password = AndroidUtils.getGlobal(GlobalVars.LOGIN,
					GlobalVars.LOGIN_PASSWORD, LoginActivity.this);
			buildRequestLogin(username, password);
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// System.exit(1);
	}

}
